package com.bbx.taxi.client.Activity.Menu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import butterknife.InjectView;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.msg.CouponMsg;
import com.bbx.api.sdk.model.passanger.Coupon;
import com.bbx.api.sdk.model.passanger.Return.Coupon.CouponList;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Coupons;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.CouponNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.MainActivity;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.CouponAdapter;
import com.bbx.taxi.client.Bean.Extra.ClauseMsg;
import com.bbx.taxi.client.DB.CouponDB;
import com.bbx.taxi.client.DB.LineDB;
import com.example.loadview.LoadingDialog;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;

public class CouponActivity extends BaseBBXActivity implements CouponMsg,OnLoadListener,OnRefreshListener{
	@InjectView(R.id.MyListView)
	MyListView mMyListView;
	@InjectView(R.id.pullToRefreshLayout)
	PullToRefreshLayout pullToRefreshLayout;
	@InjectView(R.id.layout_nodata)
	LinearLayout layout_nodata;
	private CouponAdapter mCouponAdapter;
	private List<Coupons> list;
	private int start_id = 0;
	/** 加载跟刷新的数量 */
	private int num = 10;
	private CouponDB db_coupon;// 优惠劵数据库
	private Handler handler = new Handler();
	private CouponTask mCouponTask;
	private LineDB db_line;// 线路数据库
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_coupon);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initView() {
		setTitle(true,getString(R.string.coupon_title), -1, getString(R.string.coupon_rule));
		db_line=new LineDB(context);
		db_coupon = new CouponDB(this);
		initMyListView();
		list = new ArrayList<Coupons>();
		mCouponAdapter = new CouponAdapter(this, list);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View headerview = inflater.inflate(R.layout.headerview, null);
		//【主要，添加headerview，则在OnItenClick中的Position就会错乱】
		mMyListView.addHeaderView(headerview,null,false);
		mMyListView.setAdapter(mCouponAdapter);
		onReadDB();
	}

	@Override
	protected void initData() {
	}

	private void initMyListView() {
		pullToRefreshLayout.setOnRefreshListener(this);
	    mMyListView.setOnLoadListener(this);
	    mMyListView.setEmptyView(layout_nodata);
	    mMyListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO 【修正有Header的ListView的position的BUG】  
				int headerViewsCount = mMyListView.getHeaderViewsCount();//得到header的总数量  
				//【得到新的修正后的position】  
				int newPosition = position - headerViewsCount; 
			}
		});
	}

	private void refresh() {
		start_id = 0;
		getCoupon(0);
	}

	private void load() {
		getCoupon(1);
	}

	/**
	 * 获取优惠劵
	 */
	private void getCoupon(int type) {
		Coupon mCoupon = new Coupon(context);
		mCoupon.uid = mApplication.getUid();
		mCoupon.access_token = mApplication.getToken();
		mCoupon.startid = start_id + "";
		mCoupon.num = num + "";
		mCouponTask = new CouponTask(context, mCoupon, type);
		mCouponTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private class CouponTask extends BaseAsyncTask {

		private Coupon mCoupon;
		private int type;// 0为刷新，1为加载

		public CouponTask(Activity context, Coupon mCoupon, int type) {
			super(context, false);
			this.mCoupon = mCoupon;
			setType(type);
			setIsReturnString(true);
		}

		@Override
		public void onSuccess(Object object) {
			if (object != null) {
				CouponList mCouponList = new CouponList();
				JSONArray ja_CouponList;
				try {
					List<Coupons> coupons_list = new ArrayList<Coupons>();
					JSONObject json = new JSONObject((String) object);
					ja_CouponList = json.getJSONArray(msg_coupons);
					for (int i = 0; i < ja_CouponList.length(); i++) {
						Coupons mCoupons = new Coupons();
						JSONObject jo = new JSONObject(ja_CouponList.get(i)
								.toString());
						mCoupons.setId(Integer.parseInt(jo.getString(msg_id)));
						mCoupons.setSum(Integer.parseInt(jo.getString(msg_sum)));
						mCoupons.setExpire_time(jo.getString(msg_expire_time));
						try{
						JSONObject jo_metadata = new JSONObject(
								jo.getString(msg_metadata));
						Metadata mMetadata = new Metadata();	                   						
						JSONArray ja_line =new JSONArray(jo_metadata.getString(msg_usableline));
						List<String> list_line=new ArrayList<String>();
						for(int j=0;j<ja_line.length();j++){
							String str_line=ja_line.get(j).toString();
							list_line.add(str_line);
						}
						mMetadata.setUsableline(list_line);
						
						mMetadata.setUsabletype(jo_metadata
								.getString(msg_usabletype));
						mMetadata.setUsableorder(jo_metadata
								.getString(msg_usableorder));
						mMetadata.setUsabletime(jo_metadata
								.getString(msg_usabletime));
						mCoupons.setMetadata(mMetadata);
						}
						catch(Exception e){}
						coupons_list.add(mCoupons);
					}
					mCouponList.setCouponList(coupons_list);
				} catch (JSONException e) {
				}

				if (getType() == 0) {// 刷新
					list.clear();
					int size=0;
					if (mCouponList.getCouponList() != null
							&& !mCouponList.getCouponList().isEmpty()) {
						list.addAll(mCouponList.getCouponList());
//						start_id =getStarId(list);
						start_id=mCouponList.getCouponList().get(mCouponList.getCouponList().size()-1).getId()+1;
						db_coupon.onDelete();
						db_coupon.onWriteDB(list);
						size=mCouponList.getCouponList().size();
					} else {
						onDeleteDB();
					}
					pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
					setLine_CN();
					notifyDataSetChanged(mCouponAdapter,size);
					if (loaddialog != null) {
						loaddialog.onDismiss();
					}
				} else if (getType() == 1) {// 加载
//					list.clear();
					int size=0;
					if (mCouponList.getCouponList() != null
							&& !mCouponList.getCouponList().isEmpty()) {
						size=mCouponList.getCouponList().size();
						list.addAll(mCouponList.getCouponList());
//						start_id =getStarId(list);
						start_id=mCouponList.getCouponList().get(mCouponList.getCouponList().size()-1).getId()+1;
//						db_coupon.onWriteDB(list); 
						size=mCouponList.getCouponList().size();
						mMyListView.setHasMoreData(true);
					} else {
						mMyListView.setHasMoreData(false);
						ToastUtil.showToast(context,R.string.in_the_end);
					}
					setLine_CN();
					notifyDataSetChanged(mCouponAdapter,size);
				}
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			if (getType() == 0) {// 刷新
				pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
				ToastUtil.showToast(context, R.string.no_network);
			} else if (getType() == 1) {// 加载
				ToastUtil.showToast(context, R.string.load_fail);
			}
			if (loaddialog != null) {
				loaddialog.onDismiss();
			}
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mCoupon).getJson();
			return new CouponNet(context, json);
		}

	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	/**
	 * 刚进来的时候读取的
	 */
	private void onReadDB() {
		new AsyncTask<Void, Void, Void>(){
			
			@Override
			protected void onPreExecute() {
				if (loaddialog != null && !loaddialog.isShowing()) {
					loaddialog.show();
				}
				super.onPreExecute();
			}
			protected Void doInBackground(Void... params) {
				list.clear();
				list.addAll(db_coupon.onReadDB(-1, num));
				setLine_CN();
				return null;
				
			}
			protected void onPostExecute(Void result) {	
				notifyDataSetChanged(mCouponAdapter,list.size());
				refresh(); // 主动下拉刷新所有的订单
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * 删除所有数据
	 */
	public void onDeleteDB() {
		db_coupon.onDelete();
	}

	protected void onDestroy() {
		if (mCouponTask != null
				&& mCouponTask.getStatus() != AsyncTask.Status.FINISHED)
			mCouponTask.cancel(true);
		super.onDestroy();

	}

	/**
	 * 刷新或加载出几个size
	 */
	public void notifyDataSetChanged(BaseAdapter adapter,int size) {
		for(int i=list.size()-1;i>=0;i--){
			// 没有过期
			if (((Long.parseLong(list.get(i).getExpire_time()) * 1000) >= new Date()
					.getTime())
					|| Long.parseLong(list.get(i).getExpire_time()) == 0) {
				
			}else{
				list.remove(i);
			}
		}
		adapter.notifyDataSetChanged();
		if (size >= num) {
			mMyListView.setHasMoreData(true);
		}else{
			mMyListView.setHasMoreData(false);
		}
		onisShowNodata(adapter);
	}

	public void onisShowNodata(BaseAdapter adapter) {
//		if (adapter.getCount() == 0) {
//			layout_nodata.setVisibility(View.VISIBLE);
//		} else {
//			layout_nodata.setVisibility(View.GONE);
//		}
	}
    @Override
    public void onClick(View v) {
    	switch(v.getId()){
    	case R.id.tv_right:
    		startActivity(new Intent(this, ClauseActivity.class).putExtra(
					ClauseMsg.extra_clause, ClauseMsg.CLAUSE_COUPON));
    		break;
    	default:
        	super.onClick(v);
    		break;
    	}

    }
    public int getStarId(List<Coupons> list){
    	int start_id=0;
    	for(int i=0;i<list.size();i++){
    		if(list.get(i).getId()>start_id){
    			start_id=list.get(i).getId();
    		}
    	}
    	//最后一定要+1，用于拉取下一段数据开始的id
		return start_id+1;
    	
    }
    /**
     * 刷新或加载出几个Size
     */
    public void setLine_CN(){
    	String str_line_num = SharedPreUtil.getStringValue(this, SharedPreEncryptUtil.list_line_num, "");
    	String str_line_cn = SharedPreUtil.getStringValue(this, SharedPreEncryptUtil.list_line_cn, "");
    	final List<String> list_line_num=Arrays.asList(str_line_num.replace("[","").replace("]", "").trim().split(","));
    	final List<String> list_line_cn=Arrays.asList(str_line_cn.replace("[","").replace("]", "").trim().split(","));
		for(int z=0;z<list.size();z++){
    		String name;
    		if(list.get(z).getMetadata()!=null){
    			List<String> list_line=list.get(z).getMetadata().getUsableline(); 
    			if(list_line!=null){
    				String line="";
    				for(int i=0;i<list_line.size();i++){
    					if(list_line.get(i).trim().equals("*")){
    						line=getString(R.string.line_name_all);
    						break;
    					}
    					else {
    						for(int j=0;j<list_line_num.size();j++){
    							if(list_line.get(i).trim().equals(list_line_num.get(j).trim())){
    								if(i!=0&&list_line.size()!=1){
		    							line+="、";
		    						}
    								line=line+list_line_cn.get(j);			
		    						break;
		    					}
    						}
    					
    					}
    				}
    				//去掉、开头的字，如“、厦门到漳州”
    				 if(line.startsWith("、")){
    					if(line.length()>1){
    						line=line.substring(1,line.length());
    					}
    				}
    				//获取不到线路，则默认全部路线
    				if(line.equals("")){
    					name="";
    				}
    				else{
    					name=String.format(getString(R.string.line_name), line);
    				}
    				list.get(z).setLine_CN(name);
    			}
    		}
    	}

		for(int i=list.size()-1;i>=0;i--){
			if(list.get(i).getLine_CN()==null){
				list.remove(i);
			}else if(list.get(i).getLine_CN()!=null&&list.get(i).getLine_CN().equals("")){
				list.remove(i);
			}
		}    	
    }

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		refresh();
	}

	@Override
	public void onLoad(PullableListView pullableListView) {
		load();
	}
}
